package com.project.controller;

import com.project.bean.PurchaseBean;
import com.project.bean.StockBean;
import com.project.bean.UserBean;
import com.project.service.IPurchaseService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequiresPermissions("purchase")
@RequestMapping("purchase")
public class PurchaseController {
    @Autowired
    private IPurchaseService purchaseService;

    @RequestMapping("findAll")
    public List<PurchaseBean> findAll(HttpServletRequest request) {
//      根据登录采购员的session中的真实姓名 查询采购车信息，返回采购车的集合
        UserBean user = (UserBean) request.getSession().getAttribute("loginUser");//得到当前登录用户的对象
        return purchaseService.findAll(user.getName());
    }

    @RequestMapping("updateInfo")
    public String updateInfo(Integer id, Integer price, Integer num) {
        //通过id修改采购的价格和采购数量
        purchaseService.updateInfo(id, price, num);
        return "ok";
    }

    @RequestMapping("remove")
    public String remove(Integer id) {
        // 通过采购车id移除购物车内的商品
        purchaseService.remove(id);
        return "ok";
    }

    @RequestMapping("add")
    public String add(HttpServletRequest request, MultipartFile file, StockBean stockBean, Integer number) throws IOException {//添加商品
        if (number == null) {
            number = 1;
        }
        String fileName = "";
        if (file != null) {
            fileName = file.getOriginalFilename();
            fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
            file.transferTo(new File("E:/download/java/lovo/java/HomeWork/itemTwoSystem/afteritem/src/main/resources/static/img/" + fileName));
        }
        stockBean.setImgPath(fileName);
        UserBean user = (UserBean) request.getSession().getAttribute("loginUser");//得到当前登录用户的对象
        purchaseService.add(user.getName(), stockBean, number);
        return "ok";
    }




    @RequestMapping("joinStock")
    public String joinStock(String supplierName, HttpServletRequest request) {//入库
        UserBean user = (UserBean) request.getSession().getAttribute("loginUser");//得到当前登录用户的对象
        purchaseService.joinStock(supplierName, user.getName());//入库
        return "ok";
    }
}
